package com.xjh.serverinspect.security.advice;

import com.xjh.serverinspect.security.NoResponseEncrypt;
import com.xjh.serverinspect.security.ResponseBodyHandler;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.List;

/**
 * <p>
 * 响应体加密
 * </p>
 *
 * @author xujinghui
 * @since 2024-12-12
 */
@RestControllerAdvice
public class ResponseBodyEncodeAdvice implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> clazz) {
        NoResponseEncrypt annotation = methodParameter.getMethodAnnotation(NoResponseEncrypt.class);
        return annotation == null;
    }

    @Override
    public Object beforeBodyWrite(Object data, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> clazz, ServerHttpRequest req, ServerHttpResponse resp) {
        List<String> headers = req.getHeaders().get("X-Encrypt");

        if (headers == null || headers.isEmpty())
            throw new RuntimeException("缺失请求头X-Encrypt");

        try {
            return ResponseBodyHandler.encrypt(data, req);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
